/**
 * Description:该类主要用于创建一个下拉列表框
 * Copyright: 成都和为科技有限公司 2012
 * 
 * 属性：
 *   datasource - 数据资源.对应服务器端action
 *   type -  数据类型，默认为code.自动加上valuetag,displaytag,submittag. 可选data
 *   coderes -  当type为code使用，传编码类型
 *   describle - 下拉列表描述
 *   valuetag - 当数据资源为DataService时,选中值对应DataService结果的列名
 *   displaytag - 当数据资源为DataService时, 显示值对应DataService结果的列名
 *   submittag - 除了提交valuetag到服务器，还会组装submittag内容到服务器.
 *      如:path="sex", submittag="{'name':'sexname'}"  服务器端接收到的数据为sex:男, name:1
 *   load - 是否初始化加载值.默认为true 方法：
 *   params - 查询默认参数
 * 事件:
 *  initdata - 下拉列表数据加载前调用
 *  beforeLoad - 加载数据前调用,用于改变查询参数
 *  onload - 下拉列表数据加载完成调用事件
 *  onchange - 改变值
 */
function ComboBox() {
}

ComboBox.inherit(Input);

/**
 * 初始化方法
 */
ComboBox.prototype.init = function() {
	ComboBox.base.init.call(this);
}

/**
 * 创建HTML节点
 */
ComboBox.prototype.create = function() {
	this._html = document.createElement("div");
	$(this._html).append("<select class='form-control'></select>");
}

/**
 * 初始化加载
 */
ComboBox.prototype.initLoad = function() {
	ComboBox.base.initLoad.call(this);
	if (this.getAttribute().params) {
	    var params = this.getAttribute().params;
        if(typeof(params) == "object"){
            params = JSON.stringify(params);
        }
//        var sParam = this.getAttribute().params.replaceAll("'","\"");
        var sParam = params.replaceAll("'","\"");
		var oParam = JSON.parse(sParam);
		this._queryParam = oParam;
	} else {
		this._queryParam = new Object();
		this.triggerAttributeEvent("beforeload");
	}
	if (!this.getAttribute().type || this.getAttribute().type == "code") {
		if (!this.getAttribute().type)
			this.getAttribute().type = "code";
		if (!this.getAttribute().displaytag)
			this.getAttribute().displaytag = "cn";
		if (!this.getAttribute().valuetag)
			this.getAttribute().valuetag = "cn";
		if (!this.getAttribute().submittag)
			this.getAttribute().submittag = "{'" + this.getAttribute().path
					+ "dm':'dm'}";
		this._queryParam.type = this.getAttribute().coderes;
	}
	this._load = false;
	if (this.getAttribute().load != "false") {
		this.loadData();
	}
	var othis = this;
	$("select", this.getHTML()).bind("change", function(e) {
		var oSelect = e.currentTarget;
		othis._result = $("option:selected", oSelect)[0].result;
		othis.setValidate(true);
		othis.triggerAttributeEvent("onchange", othis._result);
		othis.triggerAttributeEvent("validate", othis._result);
		othis.showError();
	});
}

/**
 * 加载数据
 * @param {} oParam
 */
ComboBox.prototype.loadData = function() {
	$("select option", this._html).remove();
	if (this._attr.describle) {
		$("select", this.getHTML()).append(
				"<option value='' style='color:#aaaaaa'>---"
						+ this._attr.describle + "---</option>");
	}
	if (this.getDataSource()) {
		var othis = this;
		var oReq = new Object();
		oReq.params = this._queryParam;
		this._load = false;
		
		this.getDataSource().queryData(oReq, true, function(oResult) {
			var valueTag = othis.getAttribute().valuetag;
			var displayTag = othis.getAttribute().displaytag;
            othis.triggerAttributeEvent("initdata", oResult.records);
			othis.buildData(oResult.records, valueTag, displayTag);
			othis.onload(oResult.records);
			othis.triggerAttributeEvent("onload", oResult.records);
			othis._load = true;
			
			if (othis._attr.disabled == "true") {
				othis.setDisable();
			}
		});
	}
}

/**
 * 建立数据
 * 
 * @param {} oResult 结果值
 * @param {} valueTag 值标识
 * @param {} displayTag 显示标识
 */
ComboBox.prototype.buildData = function(oResult, valueTag, displayTag) {
	if (!oResult) return;
	for ( var i = 0; i < oResult.length; i++) {
		var or = oResult[i];
		var option = document.createElement("option");
		option.result = or;
		var value = this.valueItem(or, valueTag);
		var text = this.valueItem(or, displayTag);
		$(option).attr("value", value);
		$(option).text(text);
		$("select", this.getHTML()).append(option);
	}
}

/**
 * 如果未加载完成设置了值的,等加载完成再设置值.
 */
ComboBox.prototype.onload = function() {
	if (this._setValue) {
		this.setValue(this._setValue);
		this._setValue = null;
	}
}

/**
 * 根据查询条件重建立下拉列表
 * 
 * @param {} oParam
 */
ComboBox.prototype.reBuild = function(oParam) {
	if (oParam)
		this._queryParam = oParam;
	this.loadData();
}

/**
 * 设置数据集
 * @param {} oData 数组对象
 */
ComboBox.prototype.setData = function(oData) {
	this.getDataSource().setData(oData);
	this.loadData();
}

/**
 * 获得选择结果
 * @return {}
 */
ComboBox.prototype.getResult = function() {
	return this._result;
}

/**
 * 绑定当前控件值
 */
ComboBox.prototype.setValue = function(value, oData) {
	if (!value || value == "") {
		this.changeSelectByIndex(0);
		this._result = new Object();
		return;
	}
	//未加载完成数据，等加载完成回调设值
	if (!this._load) {
		this._setValue = value;
	}
	for ( var i = 0; i < $("option", this._html).length; i++) {
		var option = $("option", this._html)[i];
		//如果是编码, 支持通过dm选择
		if (this.getAttribute().type == "code") {
			var result = option.result;
			if (result && value == result.dm) {
				option.selected = true;
			}
		}
		if (option.value == value) {
			option.selected = true;
		} else if ($(option).text() == value) {
			//在IE8下option.text是取不到值的，需要采用$(option).text或者采用option.innerText才行
			option.selected = true;
		}
	}
	
	// 结果对象
	if ($("option:selected", this.getHTML()).length > 0)
		this._result = $("option:selected", this.getHTML())[0].result;
}

/**
 * 设置显示
 */
ComboBox.prototype.setText = function(value) {
	this.setValue(value);
}

/**
 * 获取当前控件的值。需要提交到数据库
 */
ComboBox.prototype.getValue = function(oData) {
	this.buildSubmit(oData);
	return $("select option:selected", this.getHTML()).val();
}

/**
 * 获取当前控件的显示值。
 */
ComboBox.prototype.getText = function() {
    return $("select option:selected", this.getHTML()).text();
}

ComboBox.prototype.hasValue = function(value) {
	for ( var i = 0; i < $("option", this._html).length; i++) {
		var option = $("option", this._html)[i];
		if ($(option).val() == value || $(option).text() == value) {
			return true;
		}
	}
	return false;
}

/**
 * 改变当前控件的值通过每个item的值
 * @param trigger 是否触发change事件
 */
ComboBox.prototype.changeSelectByValue = function(value, trigger) {
	for ( var i = 0; i < $("option", this._html).length; i++) {
		var option = $("option", this._html)[i];
		if (option.value == value) {
			option.selected = true;
			if (trigger) {
				this.setValidate(true);
				this._result = $("option:selected", this.getHTML())[0].result;
				this.triggerAttributeEvent("onchange", this._result);
				this.triggerAttributeEvent("validate", this._result);
				this.showError();
			}
			return;
		}
	}
}

/**
 * 改变当前控件的值通过每个item的索引
 */
ComboBox.prototype.changeSelectByIndex = function(index) {
	for ( var i = 0; i < $("option", this._html).length; i++) {
		var option = $("option", this._html)[i];
		if (i == index) {
			option.selected = true;
			return;
		}
	}
}

/**
 * 下拉列表增加选项
 * 
 * @param {Object} data 数据值 {name:name,value:value,result:结果集}
 */
ComboBox.prototype.addItem = function(data) {
	if (data && data.name && data.value != "undefined") {
		var option = document.createElement("option");
		option.result = data.result;
		var value = data.value;
		var text = data.name;
		$(option).attr("value", value);
		$(option).text(text);
		$("select", this.getHTML()).append(option);
	}
}

/**
 * 下拉列表增加选项
 * 
 * @param {Object} data 数据值 {name:name,value:value}
 */
ComboBox.prototype.addItems = function(data) {
	for ( var i = 0; i < data.length; i++) {
		this.addItem(data[i]);
	}
}

/**
 * 下拉列表移除选项
 * 
 * @param {Object} value
 */
ComboBox.prototype.removeItem = function(value) {
	$("select option[value=" + value + "]", this._html).remove();
}

ComboBox.prototype.clearItem = function() {
	$("select option", this._html).remove();
	if (this._attr.describle) {
		$("select", this.getHTML()).append(
				"<option value='' style='color:#aaaaaa'>---"
						+ this._attr.describle + "---</option>");
	}
}

ComboBox.prototype.setParam = function(oParam) {
	for(var i in oParam){
		this._queryParam[i] = oParam[i]
	}
}

ComboBox.prototype.getParam = function() {
	return this._queryParam;
}

/**
 * 设置为可编辑
 */
ComboBox.prototype.setEnable = function() {
	$(this._html).removeAttr("disabled");
	$("select", this._html)[0].disabled = false;
	if (this._attr.describle)
		$("select option:first", this.getHTML()).text("---" + this._attr.describle + "---");
		
	//show icon
	var width = $(this._html).width();
	$("select", this._html).css({
		"width": width
	});
	this._disable = false;
}

/**
 * 设置为只读
 */
ComboBox.prototype.setDisable = function() {
	$("select", this._html).attr("disabled", "true");
	if (this._attr.describle)
		$("select option:first", this.getHTML()).text("");
	//hide icon
	var width = $(this._html).width();
	$(this._html).css({
		"overflow": "hidden"
	});
	$("select", this._html).css({
		"width": width + 40
	});

	this._disable = true;
}
